package com.googlecode.javaexamples.multithreading.ringbuffer;

public class ReaderThread extends Thread {
    private boolean needToStop;
    private Object lockObject;
    private RingBuffer<String> buffer;
    private RingBuffer<String> outputBuffer;

    public ReaderThread(RingBuffer<String> buffer,
            RingBuffer<String> outBuffer, Object lockObject) {
        super();
        this.buffer = buffer;
        this.outputBuffer = outBuffer;
        this.setDaemon(true);
        this.lockObject = lockObject;
        this.setName("Reader " + this.getName());
    }

    public void run() {
        while (!needToStop) {
            synchronized (lockObject) {
                if (buffer.elementCount() > 0
                        && (outputBuffer.elementCount() < outputBuffer.size())) {
                    String message = buffer.pop();
                    outputBuffer.push("Thread "
                            + Thread.currentThread().getName()
                            + " put message: " + message);
                    lockObject.notifyAll();
                } else {
                    try {
                        lockObject.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public void stopReader() {
        needToStop = true;
    }
}
